package com.sk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.sk.constant.Constant;
import com.sk.dto.WxLogin2Dto;
import com.sk.entity.AppletUser;
import com.sk.entity.vo.AppletUserVo;
import com.sk.entity.vo.WeiXinLoginVo;
import com.sk.enums.LogicDelEnum;
import com.sk.exception.WechatLoginException;
import com.sk.mapper.AppletUserMapper;
import com.sk.res.CommonResponseDto;
import com.sk.service.IAppletUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sk.service.IWechatService;
import com.sk.stone.utils.RedisUtil;
import com.sk.util.ConvertBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

/**
 * <p>
 * 小程序用户信息表 服务实现类
 * </p>
 *
 * @author jiaok
 * @since 2024-04-24
 */
@Service
@Slf4j
public class AppletUserServiceImpl extends ServiceImpl<AppletUserMapper, AppletUser> implements IAppletUserService {

    @Autowired
    private RedisUtil redisUtil;


    @Resource
    private IWechatService iWechatService;


    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public WxLogin2Dto weiXinLogin(WeiXinLoginVo weiXinLoginReq) {

        WxLogin2Dto wxLogin2Dto=new WxLogin2Dto();
        log.info("本次调用微信登录的入参为:{}", JSONObject.toJSON(weiXinLoginReq));
        String code = weiXinLoginReq.getLoginCode();
        String phoneCode = weiXinLoginReq.getPhoneCode();

        String redisKey= Constant.REDIS_WECHAT_LOGIN+code;
        boolean hasOpenidCache=redisUtil.hasKey(redisKey);
        String mobile="";
        String openid = "";
        String unionId = "";
        String sessionKey = "";

        if (hasOpenidCache){
            //从缓存中获取openid----用户在小程序中的唯一标识
            openid = redisUtil.get(redisKey);
        }else {
            //从微信服务器获取
            JSONObject message = iWechatService.login2(code);
            log.info("调用微信登录的返回结果为:{}",JSONObject.toJSON(message));
            if (message.get("errcode") != null) {
                log.error("调用微信登录的返回结果为:{}",JSONObject.toJSON(message));
                throw new WechatLoginException(message.get("errcode").toString(),message.get("errmsg").toString());
            }
            openid = message.getString("openid");
            unionId = message.getString("unionid");
            sessionKey = message.get("session_key").toString();

            // TODO: 2024-04-25 获取手机号接口 后续开放
//            JSONObject jsonObject = iWechatService.getPhoneNumber(phoneCode);
//            log.info("调用微信解析手机号接口的返回结果为:{}",JSONObject.toJSON(jsonObject));
//            if (!jsonObject.get("errcode").toString().equals("0")) {
//                log.error("调用微信解析手机号接口的返回结果为:{}",JSONObject.toJSON(jsonObject));
//                throw new WechatLoginException(jsonObject.get("errcode").toString(),jsonObject.get("errmsg").toString());
//            }
//            JSONObject phoneInfo=  JSONObject.parseObject(jsonObject.get("phone_info").toString());
//            mobile=phoneInfo.getString("phoneNumber");

        }

        //根据openId判断当前登录用户是否已经存在
        QueryWrapper<AppletUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",openid);
        AppletUser appletUser = baseMapper.selectOne(queryWrapper);

        wxLogin2Dto.setOpenid(openid);
        wxLogin2Dto.setExist(1);
        wxLogin2Dto.setSessionKey(sessionKey);

        if (ObjectUtils.isNotEmpty(appletUser)){
//            当前用户已存在  判断手机号是否需要更新
//            if (StringUtils.isBlank(mobile) && StringUtils.isBlank(appletUser.getMobile()) && !appletUser.getMobile().equals(mobile)){
//                appletUser.setMobile(mobile);
//                baseMapper.updateById(appletUser);
//            }

        }else {
            appletUser=new AppletUser();
//            当前用户不存在
            appletUser.setOpenId(openid);
            appletUser.setUnionId(unionId==null?"":unionId);
            appletUser.setPass(Constant.DEFAUT_PASSWORD);
            appletUser.setIsShow(Constant.STATUS_ENABLE);
            appletUser.setCreateUser(Constant.SYSTEM_USER_CODE);
            appletUser.setCreateUserName(Constant.SYSTEM_USER_CN);
            appletUser.setCreateTime(LocalDateTime.now());
            appletUser.setIsDeleted(LogicDelEnum.IS_DELETE_NO.getCode());
            appletUser.setIsFocusWechatService(0);
            this.save(appletUser);

        }

        return wxLogin2Dto;
    }

    @Override
    public CommonResponseDto saveAppletUser(AppletUserVo appletUserVo) {

        AppletUser appletUser = ConvertBeanUtils.convert(appletUserVo, AppletUser.class);
        appletUser.setCreateUser(Constant.SYSTEM_USER_CODE);
        appletUser.setCreateUserName(Constant.SYSTEM_USER_CN);
        appletUser.setCreateTime(LocalDateTime.now());
        appletUser.setIsDeleted(LogicDelEnum.IS_DELETE_NO.getCode());
        appletUser.setIsFocusWechatService(0);
        this.save(appletUser);

        return CommonResponseDto.success();
    }
}
